from pprint import pprint

from aliyunsdkcore.profile import region_provider
from aliyunsdkcore.acs_exception import exceptions as exs
from aliyunsdkcore.acs_exception import error_code, error_msg
from aliyunsdkcore.http.http_response import HttpResponse
from aliyunsdkcore.request import AcsRequest
import httplib

from aliyunsdkcore.http.http_request import HttpRequest

try:
    from lxml import etree as ET
except ImportError:
    from xml.etree import ElementTree as ET

try:
    import simplejson as json
except ImportError:
    import json

from libcloud.common.base import ConnectionUserAndKey, JsonResponse


# make new function to get libcloud
# WARNING : Aliyun
class AliyunHTTPLibHttpResponse(HttpResponse):
    def __init__(self, host="", url="/", method="GET", headers={}, protocol='http', content=None, port=None,
                 key_file=None, cert_file=None):
        HttpRequest.__init__(self, host=host, url=url, method=method, headers=headers)
        self.__ssl_enable = False
        if protocol is 'https':
            self.__ssl_enable = True
        self.__key_file = key_file
        self.__cert_file = cert_file
        self.__port = port
        self.__connection = None
        self.set_body(content)

    def get_httplib_response(self):
        if self.get_ssl_enabled():
            return self.get_httplib_https_response_object()
        else:
            return self.get_httplib_http_response_object()

    def get_httplib_http_response_object(self):
        if self.__port is None or self.__port == "":
            self.__port = 80
        try:
            self.__connection = httplib.HTTPConnection(self.get_host(), self.__port)
            self.__connection.connect()
            self.__connection.request(method=self.get_method(), url=self.get_url(), body=self.get_body(),
                                      headers=self.get_headers())
            response = self.__connection.getresponse()
            return response
        except Exception as e:
            return None, None
        finally:
            self.__close_connection()

    def get_httplib_https_response_object(self):
        if self.__port is None or self.__port == "":
            self.__port = 443
        try:
            self.__port = 443
            self.__connection = httplib.HTTPSConnection(self.get_host(), self.__port, cert_file=self.__cert_file,
                                                        key_file=self.__key_file)
            self.__connection.connect()
            self.__connection.request(method=self.get_method(), url=self.get_url(), body=self.get_body(),
                                      headers=self.get_headers())
            response = self.__connection.getresponse()
            return response
        except Exception as e:
            return None, None
        finally:
            self.__close_connection()

    def set_ssl_enable(self, enable):
        self.__ssl_enable = enable

    def get_ssl_enabled(self):
        return self.__ssl_enable

    def get_response(self):
        if self.get_ssl_enabled():
            return self.get_https_response()
        else:
            return self.get_http_response()

    def get_response_object(self):
        if self.get_ssl_enabled():
            return self.get_https_response_object()
        else:
            return self.get_http_response_object()

    def get_http_response(self):
        if self.__port is None or self.__port == "":
            self.__port = 80
        try:
            self.__connection = httplib.HTTPConnection(self.get_host(), self.__port)
            self.__connection.connect()
            self.__connection.request(method=self.get_method(), url=self.get_url(), body=self.get_body(),
                                      headers=self.get_headers())
            response = self.__connection.getresponse()
            return response.getheaders(), response.read()
        except Exception as e:
            return None, None
        finally:
            self.__close_connection()

    def get_http_response_object(self):
        if self.__port is None or self.__port == "":
            self.__port = 80
        try:
            self.__connection = httplib.HTTPConnection(self.get_host(), self.__port)
            self.__connection.connect()
            self.__connection.request(method=self.get_method(), url=self.get_url(), body=self.get_body(),
                                      headers=self.get_headers())
            response = self.__connection.getresponse()
            return response.status, response.getheaders(), response.read()
        except Exception as e:
            return None, None
        finally:
            self.__close_connection()

    def get_https_response(self):
        if self.__port is None or self.__port == "":
            self.__port = 443
        try:
            self.__port = 443
            self.__connection = httplib.HTTPSConnection(self.get_host(), self.__port, cert_file=self.__cert_file,
                                                        key_file=self.__key_file)
            self.__connection.connect()
            self.__connection.request(method=self.get_method(), url=self.get_url(), body=self.get_body(),
                                      headers=self.get_headers())
            response = self.__connection.getresponse()
            return response.getheaders(), response.read()
        except Exception as e:
            return None, None
        finally:
            self.__close_connection()

    def get_https_response_object(self):
        if self.__port is None or self.__port == "":
            self.__port = 443
        try:
            self.__port = 443
            self.__connection = httplib.HTTPSConnection(self.get_host(), self.__port, cert_file=self.__cert_file,
                                                        key_file=self.__key_file)
            self.__connection.connect()
            self.__connection.request(method=self.get_method(), url=self.get_url(), body=self.get_body(),
                                      headers=self.get_headers())
            response = self.__connection.getresponse()
            return response.status, response.getheaders(), response.read()
        except Exception as e:
            return None, None
        finally:
            self.__close_connection()

    def __close_connection(self):
        try:
            if self.__connection is not None:
                self.__connection.close()
        except Exception as e:
            pass


pass


class AliyunAcsClient(object):
    def __init__(self, ak, secret, region_id, auto_retry=True, max_retry_time=3, user_agent=None, port=80):
        self.__max_retry_num = max_retry_time
        self.__auto_retry = auto_retry
        self.__ak = ak
        self.__secret = secret
        self.__region_id = region_id
        self.__user_agent = user_agent
        self.__port = port

    def get_region_id(self):
        return self.__region_id

    def get_access_key(self):
        return self.__ak

    def get_access_secret(self):
        return self.__secret

    def is_auto_retry(self):
        return self.__auto_retry

    def get_max_retry_num(self):
        return self.__max_retry_num

    def get_user_agent(self):
        return self.__user_agent

    def set_region_id(self, region):
        self.__region_id = region

    def set_access_key(self, ak):
        self.__ak = ak

    def set_access_secret(self, secret):
        self.__secret = secret

    def set_max_retry_num(self, num):
        """
        set auto retry number
        :param num: Numbers
        :return: None
        """
        self.__max_retry_num = num

    def set_auto_retry(self, flag):
        """
        set whether or not the client perform auto-retry
        :param flag: Booleans
        :return: None
        """
        self.__auto_retry = flag

    def set_user_agent(self, agent):
        """
        User agent set to client will overwrite the request setting.
        :param agent:
        :return:
        """
        self.__user_agent = agent

    def do_action(self, acs_request):
        ep = region_provider.find_product_domain(self.get_region_id(), acs_request.get_product())
        if ep is None:
            raise exs.ClientException(error_code.SDK_INVALID_REGION_ID, error_msg.get_msg('SDK_INVALID_REGION_ID'))
        if not isinstance(acs_request, AcsRequest):
            raise exs.ClientException(error_code.SDK_INVALID_REQUEST, error_msg.get_msg('SDK_INVALID_REQUEST'))
        try:
            # style = acs_request.get_style()
            content = acs_request.get_content()
            method = acs_request.get_method()
            header = acs_request.get_signed_header(self.get_region_id(), self.get_access_key(),
                                                   self.get_access_secret())
            if self.get_user_agent() is not None:
                header['User-Agent'] = self.get_user_agent()
                header['x-sdk-client'] = 'python/2.0.0'
            protocol = acs_request.get_protocol_type()
            prefix = self.__replace_occupied_params(acs_request.get_domain_pattern(), acs_request.get_domain_params())
            url = acs_request.get_url(self.get_region_id(), self.get_access_key(), self.get_access_secret())
            if prefix is None:
                response = HttpResponse(ep, url, method, {} if header is None else header, protocol, content,
                                        self.__port)
            else:
                response = HttpResponse(prefix + ',' + ep, url, method, {} if header is None else header, protocol,
                                        content, self.__port)
            _header, _body = response.get_response()
            # if _body is None:
            # 	raise exs.ClientException(error_code.SDK_SERVER_UNREACHABLE, error_msg.get_msg('SDK_SERVER_UNREACHABLE'))
            return _body
        except IOError:
            raise exs.ClientException(error_code.SDK_SERVER_UNREACHABLE, error_msg.get_msg('SDK_SERVER_UNREACHABLE'))
        except AttributeError:
            raise exs.ClientException(error_code.SDK_INVALID_REQUEST, error_msg.get_msg('SDK_INVALID_REQUEST'))

    def get_response(self, acs_request):
        ep = region_provider.find_product_domain(self.get_region_id(), acs_request.get_product())
        if ep is None:
            raise exs.ClientException(error_code.SDK_INVALID_REGION_ID, error_msg.get_msg('SDK_INVALID_REGION_ID'))
        if not isinstance(acs_request, AcsRequest):
            raise exs.ClientException(error_code.SDK_INVALID_REQUEST, error_msg.get_msg('SDK_INVALID_REQUEST'))
        try:
            # style = acs_request.get_style()
            content = acs_request.get_content()
            method = acs_request.get_method()
            header = acs_request.get_signed_header(self.get_region_id(), self.get_access_key(),
                                                   self.get_access_secret())
            if self.get_user_agent() is not None:
                header['User-Agent'] = self.get_user_agent()
                header['x-sdk-client'] = 'python/2.0.0'
            protocol = acs_request.get_protocol_type()
            prefix = self.__replace_occupied_params(acs_request.get_domain_pattern(), acs_request.get_domain_params())
            url = acs_request.get_url(self.get_region_id(), self.get_access_key(), self.get_access_secret())
            if prefix is None:
                _response = HttpResponse(ep, url, method, {} if header is None else header, protocol, content,
                                         self.__port)
            else:
                _response = HttpResponse(prefix + ',' + ep, url, method, {} if header is None else header, protocol,
                                         content, self.__port)
            return _response.get_response_object()

        except IOError:
            raise exs.ClientException(error_code.SDK_SERVER_UNREACHABLE, error_msg.get_msg('SDK_SERVER_UNREACHABLE'))
        except AttributeError:
            raise exs.ClientException(error_code.SDK_INVALID_REQUEST, error_msg.get_msg('SDK_INVALID_REQUEST'))

    def __replace_occupied_params(self, pattern, params):
        if pattern is None:
            return None
        if params is None:
            return pattern
        for (k, v) in params.items():
            target = '[' + k + ']'
            pattern.replace(target, v)
        return pattern

    def get_httplib_HTTPResponse(self, acs_request):
        ep = region_provider.find_product_domain(self.get_region_id(), acs_request.get_product())
        if ep is None:
            raise exs.ClientException(error_code.SDK_INVALID_REGION_ID, error_msg.get_msg('SDK_INVALID_REGION_ID'))
        if not isinstance(acs_request, AcsRequest):
            raise exs.ClientException(error_code.SDK_INVALID_REQUEST, error_msg.get_msg('SDK_INVALID_REQUEST'))
        try:
            # style = acs_request.get_style()
            content = acs_request.get_content()
            method = acs_request.get_method()
            header = acs_request.get_signed_header(self.get_region_id(), self.get_access_key(),
                                                   self.get_access_secret())
            if self.get_user_agent() is not None:
                header['User-Agent'] = self.get_user_agent()
                header['x-sdk-client'] = 'python/2.0.0'
            protocol = acs_request.get_protocol_type()
            prefix = self.__replace_occupied_params(acs_request.get_domain_pattern(), acs_request.get_domain_params())
            url = acs_request.get_url(self.get_region_id(), self.get_access_key(), self.get_access_secret())
            if prefix is None:
                _response = AliyunHTTPLibHttpResponse(ep, url, method, {} if header is None else header, protocol,
                                                      content,
                                                      self.__port)
            else:
                _response = AliyunHTTPLibHttpResponse(prefix + ',' + ep, url, method, {} if header is None else header,
                                                      protocol,
                                                      content, self.__port)
            return _response.get_httplib_response()

        except IOError:
            raise exs.ClientException(error_code.SDK_SERVER_UNREACHABLE, error_msg.get_msg('SDK_SERVER_UNREACHABLE'))
            # except AttributeError:
            #     raise exs.ClientException(error_code.SDK_INVALID_REQUEST, error_msg.get_msg('SDK_INVALID_REQUEST'))


class AliyunGlobalConfig:
    def __init__(self):
        pass

    Format = {'JSON': 'json', 'XML': 'xml'}


class AliyunConnection(ConnectionUserAndKey):
    access_key_id = None
    access_key_secret = None

    clientCls = AliyunAcsClient

    # clientCls = AliyunClient.AcsClient

    # responseCls = AliyunResponse

    def __init__(self, access_key_id, access_key_secret, region=None, secure=True,
                 host=None, port=None, url=None, timeout=None, proxy_url=None,
                 retry_delay=None, backoff=None):
        self.access_key_id = access_key_id
        self.access_key_secret = access_key_secret

        self.responseCls = AliyunJsonResponse
        super(AliyunConnection, self).__init__(
                self.access_key_id,
                self.access_key_id,
                secure,
                host,
                port,
                url,
                timeout,
                proxy_url,
                backoff,
                retry_delay
        )

    def get_client(self,RegionId=None):
        # print "Class AliyunConnection Method get_client Debug:Run"
        # print "Class AliyunConnection Method get_client Debug:[self.access_key_id]:" + self.access_key_id
        # print "Class AliyunConnection Method get_client Debug:[self.access_key_secret]:" + self.access_key_secret
        # # print "Class AliyunConnection Method get_client Debug:[self.region_id]:" + str(self.region_id)
        # # print "Class AliyunConnection Method get_client Debug:[self.driver]:" + type(self.driver)
        if RegionId is None:
            self.client = self.clientCls(self.access_key_id, self.access_key_secret, self.driver.region_id)
        else:
            self.client = self.clientCls(self.access_key_id, self.access_key_secret, RegionId)
        return self.client


class AliyunJsonResponse(JsonResponse):
    #base
    def AliyunRequestId(self):
        return AliyunRequestId(self.parse_body())

    def AliyunPage(self):
        return AliyunPage(self.parse_body())

    #self
    def AliyunDescribeInstances(self):
        return AliyunDescribeInstances(self.parse_body())

    def AliyunDescribeInstanceTypes(self):
        return AliyunDescribeInstanceTypes(self.parse_body())

    def AliyunDescribeSnapshots(self):
        return AliyunDescribeSnapshots(self.parse_body())

    def AliyunDescribeRegions(self):
        return AliyunDescribeRegions(self.parse_body())

    def AliyunDescribeZones(self):
        return AliyunDescribeZones(self.parse_body())

    def AliyunDescribeDisks(self):
        return AliyunDescribeDisks(self.parse_body())

    def AliyunDescribeImages(self):
        return AliyunDescribeImages(self.parse_body())

    def AliyunDescribeSecurityGroups(self):
        return AliyunDescribeSecurityGroups(self.parse_body())


# class DiskItemType(object):
#     # global
#     DISK_TYPE = {'SYSTEM': 'system', 'DATA': 'data'}
#     DISK_CATEGORY = {
#         'cloud': 'cloud',
#         'cloud_efficiency': 'cloud_efficiency',
#         'cloud_ssd': 'cloud_ssd',
#         'ephemeral_ssd': 'ephemeral_ssd',
#         'ephemeral': 'ephemeral',
#     }
#     DISK_STATUS = {
#         'In_use': 'In_use',
#         'Available': 'Available',
#         'Attaching': 'Attaching',
#         'Detaching': 'Detaching',
#         'Creating': 'Creating',
#         'ReIniting': 'ReIniting',
#     }
#     DISK_DISKCARGETYPE = {
#         'PrePaid': 'PrePaid',
#         'PostPaid': 'PostPaid',
#     }
#     DiskId = None
#     RegionId = None
#     ZoneId = None
#     DiskName = None
#     Description = None
#     Type = None
#     Category = None
#     Size = -1  # GB
#     ImageId = None
#     SourceSnapshotId = None
#     ProductCode = None
#     Portable = None  # before attach&detach must check
#     Status = None
#     OperationLocks = None
#     InstanceId = None
#     Device = None
#     DeleteWithInstance = None
#     DeleteAutoSnapshot = None
#     EnableAutoSnapshot = None
#     CreationTime = None
#     AttachedTime = None
#     DetachedTime = None
#     DiskChargeType = None
#
#     def __json_deserialize__(self, tree, format):
#         pprint('Class DiskDeviceMapping Method __json_deserialize__ Debug:run')
#         self.SnapshotId = tree['SnapshotId']
#         self.DiskId = tree['DiskId']
#         self.RegionId = tree['RegionId']
#         self.ZoneId = tree['ZoneId']
#         self.DiskName = tree['DiskName']
#         self.Description = tree['Description']
#         self.Type = tree['Type']
#         self.Category = tree['Category']
#         self.Size = tree['Size']  # GB
#         self.ImageId = tree['ImageId']
#         self.SourceSnapshotId = tree['SourceSnapshotId']
#         self.ProductCode = tree['ProductCode']
#         self.Portable = tree['Portable']  # before attach&detach must check
#         self.Status = tree['Status']
#         self.OperationLocks = tree['OperationLocks']
#         self.InstanceId = tree['InstanceId']
#         self.Device = tree['Device']
#         self.DeleteWithInstance = tree['DeleteWithInstance']
#         self.DeleteAutoSnapshot = tree['DeleteAutoSnapshot']
#         self.EnableAutoSnapshot = tree['EnableAutoSnapshot']
#         self.CreationTime = tree['CreationTime']
#         self.AttachedTime = tree['AttachedTime']
#         self.DetachedTime = tree['DetachedTime']
#         self.DiskChargeType = tree['DiskChargeType']
#
#     def __xml_deserialize__(self, body, format):
#         raise NotImplementedError('xml deserialize not implemented for this type')
#
#     def __init__(self, body, format):
#         if format == AliyunGlobalConfig.Format.get('JSON'):
#             self.__json_deserialize__(body, format)
#         elif format == AliyunGlobalConfig.Format.get('XML'):
#             self.__xml_deserialize__(body, format)
#         else:
#             raise NotImplementedError(format + ' deserialize not implemented for this type , unknow format')
#
# class IpAddressSetType():
#     def __init__(self, body, format):
#         pass
#
#     IpAddress = None  # String
#
#
# class VpcAttributesType():
#     def __init__(self):
#         pass
#
#     VpcId = None
#     VSwitchId = None
#     PrivateIpAddress = []  # DataType list <IpAddressSetType>
#     NatIpAddress = None
#
#
# class EipAddressAssociateType():
#     def __init__(self):
#         pass
#
#     AllocationId = None  # String
#     IpAddress = None  # String
#     Bandwidth = None  # Integer
#     InternetChargeType = None  # String
#
#
# class RegionType(object):
#     RegionId = None  # String
#     LocalName = None  # String
#
#     def __init__(self, body, format):
#         tree = body
#         self.RegionId = tree['RegionId']
#         self.LocalName = tree['LocalName']
#         pass
#
#
# class DiskDeviceMapping(object):
#     SnapshotId = None
#     Size = None
#     Device = None
#     Format = None
#     ImportOSSBucket = None
#     ImportOSSObject = None
#
#     def __init__(self, body, format):
#         if format == 'json':
#             print 'format json'
#             self.__json_deserialize__(body, format)
#         elif format == 'xml':
#             print 'format xml'
#             self.__xml_deserialize__(body, format)
#         else:
#             print 'format error'
#             raise NotImplementedError('Unknow aliyun public request format :' + format)
#
#     def __json_deserialize__(self, body, format):
#         print "Class DiskDeviceMapping Method __json_deserialize__ Debug:run"
#         tree = body
#         self.SnapshotId = tree['SnapshotId']
#         self.Size = tree['Size']
#         self.Device = tree['Device']
#         self.Format = tree['Format']
#         self.ImportOSSBucket = tree['ImportOSSBucket']
#         self.ImportOSSObject = tree['ImportOSSObject']
#         print "Class DiskDeviceMapping Method __json_deserialize__ Debug:end"
#
#
# class ImageType(object):
#     ImageId = None
#     ImageVersion = None
#     OSType = None
#     Platform = None
#     Architecture = None
#     ImageName = None
#     Description = None
#     Size = -1
#     ImageOwnerAlias = None
#     OSName = None
#     DiskDeviceMappings = []  # Type DiskDeviceMapping
#     ProductCode = None
#     IsSubscribed = None
#     Progress = None
#     Status = None
#     CreationTime = None
#     Usage = None
#     IsCopied = None
#
#     def __init__(self, body, format):
#         if format == 'json':
#             print 'format json'
#             self.__json_deserialize__(body, format)
#         elif format == 'xml':
#             print 'format xml'
#             self.__xml_deserialize__(body, format)
#         else:
#             print 'format error'
#             raise NotImplementedError('Unknow aliyun public request format :' + format)
#
#     def __json_deserialize__(self, body, format):
#         print "Class ImageType Method __json_deserialize__ Debug:run"
#         tree = body
#         # print tree
#
#         self.ImageId = tree['ImageId']
#         self.ImageVersion = tree['ImageVersion']
#         self.OSType = tree['OSType']
#         self.Platform = tree['Platform']
#         self.Architecture = tree['Architecture']
#         self.ImageName = tree['ImageName']
#         self.Description = tree['Description']
#         self.Size = tree['Size']
#         self.ImageOwnerAlias = tree['ImageOwnerAlias']
#         self.OSName = tree['OSName']
#         self.DiskDeviceMappings = []  # Type DiskDeviceMapping
#
#         diskDeviceMappings = tree['DiskDeviceMappings']
#         for diskDeviceMapping in diskDeviceMappings['DiskDeviceMapping']:
#             self.DiskDeviceMappings.append(DiskDeviceMapping(diskDeviceMapping, format))
#
#         self.ProductCode = tree['ProductCode']
#         self.IsSubscribed = tree['IsSubscribed']
#         self.Progress = tree['Progress']
#         self.Status = tree['Status']
#         self.CreationTime = tree['CreationTime']
#         self.Usage = tree['Usage']
#         self.IsCopied = tree['IsCopied']
#
#         print "Class ImageType Method __json_deserialize__ Debug:end"
#
#
# class InstanceTypeItemType(object):
#     InstanceTypeId = None
#     CpuCoreCount = -1
#     MemorySize = -1  # GB
#     InstanceTypeFamily = None
#
#     def __init__(self, body, format):
#         if format == 'json':
#             print 'format json'
#             self.__json_deserialize__(body, format)
#         elif format == 'xml':
#             print 'format xml'
#             self.__xml_deserialize__(body, format)
#         else:
#             print 'format error'
#             raise NotImplementedError('Unknow aliyun public request format :' + format)
#
#     def __json_deserialize__(self, body, format):
#         print "Class InstanceTypeItemType Method __json_deserialize__ Debug:run"
#         tree = body
#         # print tree
#
#         self.InstanceTypeId = tree['InstanceTypeId']
#         self.CpuCoreCount = tree['CpuCoreCount']
#         self.MemorySize = tree['MemorySize']
#         self.InstanceTypeFamily = tree['InstanceTypeFamily']
#
#         print "Class InstanceTypeItemType Method __json_deserialize__ Debug:end"

# ---------------------
# Aliyun Serialization
# Self Type
class AliyunRequestId(object):
    RequestId = None

    def __init__(self, tree):
        # super(AliyunRequestId,self).__init__(body,format)
        print "Class AliyunRequestId Method __init__ Debug:run"
        self.RequestId = tree['RequestId']


class AliyunPage(object):
    PageNumber = -1
    TotalCount = -1
    PageSize = -1

    def __init__(self, tree):
        # super(AliyunPage, self).__init__(body, format)
        print "Class AliyunPage Method __init__ Debug:run"
        self.PageNumber = tree['PageNumber']
        self.TotalCount = tree['TotalCount']
        self.PageSize = tree['PageSize']


# Aliyun Base Data Type - build by type_build.py
# /usr/bin/python2.7 /home/zhanpeng/Workspace/Python/Libcloud4Aliyun/aliyun_test/type_build/type_build.py
#Aliyun Data Type : DiskItemType
class DiskItemType(object):
    DiskId = None
    RegionId = None
    ZoneId = None
    DiskName = None
    Description = None
    Type = None
    Category = None
    Size = -1  # GB
    ImageId = None
    SourceSnapshotId = None
    ProductCode = None
    Portable = None
    OperationLocks = None  # TODO:OperationLocksType
    InstanceId = None
    DeleteWithInstance = None
    DeleteAutoSnapshot = None
    EnableAutoSnapshot = None
    CreationTime = None
    AttachedTime = None
    DetachedTime = None
    DiskChargeType = None

    def __deserialize__(self, tree):
        self.DiskId = tree['DiskId']
        self.RegionId = tree['RegionId']
        self.ZoneId = tree['ZoneId']
        self.DiskName = tree['DiskName']
        self.Description = tree['Description']
        self.Type = tree['Type']
        self.Category = tree['Category']
        self.Size = tree['Size']  # GB
        self.ImageId = tree['ImageId']
        self.SourceSnapshotId = tree['SourceSnapshotId']
        self.ProductCode = tree['ProductCode']
        self.Portable = tree['Portable']
        self.OperationLocks = tree['OperationLocks']  # TODO:OperationLocksType
        self.InstanceId = tree['InstanceId']
        self.DeleteWithInstance = tree['DeleteWithInstance']
        self.DeleteAutoSnapshot = tree['DeleteAutoSnapshot']
        self.EnableAutoSnapshot = tree['EnableAutoSnapshot']
        self.CreationTime = tree['CreationTime']
        self.AttachedTime = tree['AttachedTime']
        self.DetachedTime = tree['DetachedTime']
        self.DiskChargeType = tree['DiskChargeType']

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : DiskSetType
class DiskSetType(object):
    Disk = None  # TODO:DiskItemType

    def __deserialize__(self, tree):
        self.Disk = tree['Disk']  # TODO:DiskItemType

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : ImageType
class ImageType(object):
    ImageId = None
    ImageVersion = None
    OSType = None
    Platform = None
    Architecture = None
    ImageName = None
    Description = None
    Size = -1  # image size
    ImageOwnerAlias = None
    OSName = None
    DiskDeviceMappings = []  # DiskDeviceMapping
    ProductCode = None
    IsSubscribed = None
    Progress = None
    Status = None
    CreationTime = None
    Usage = None
    IsCopied = None

    def __deserialize__(self, tree):
        self.ImageId = tree['ImageId']
        self.ImageVersion = tree['ImageVersion']
        self.OSType = tree['OSType']
        self.Platform = tree['Platform']
        self.Architecture = tree['Architecture']
        self.ImageName = tree['ImageName']
        self.Description = tree['Description']
        self.Size = tree['Size']  # image size
        self.ImageOwnerAlias = tree['ImageOwnerAlias']
        self.OSName = tree['OSName']
        self.DiskDeviceMappings = []
        diskdevicemappings = tree['DiskDeviceMappings']  # DiskDeviceMapping
        for diskdevicemapping in diskdevicemappings['DiskDeviceMapping']:
            self.DiskDeviceMappings.append(DiskDeviceMapping(diskdevicemapping))

        self.ProductCode = tree['ProductCode']
        self.IsSubscribed = tree['IsSubscribed']
        self.Progress = tree['Progress']
        self.Status = tree['Status']
        self.CreationTime = tree['CreationTime']
        self.Usage = tree['Usage']
        self.IsCopied = tree['IsCopied']

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : InstanceMonitorDataType
class InstanceMonitorDataType(object):
    InstanceId = None
    CPU = -1  #  %
    IntranetRX = -1  # kbits
    IntranetTX = -1  # kbits
    IntranetBandwidth = -1  # kbits/s
    InternetRX = -1  # kbits
    InternetTX = -1  # kbits
    InternetBandwidth = -1  # kbits/s
    IOPSRead = -1  # count/s
    IOPSWrite = -1  # count/s
    BPSRead = -1  # Byte/s
    BPSWrite = -1  # Byte/s
    TimeStamp = None

    def __deserialize__(self, tree):
        self.InstanceId = tree['InstanceId']
        self.CPU = tree['CPU']  #  %
        self.IntranetRX = tree['IntranetRX']  # kbits
        self.IntranetTX = tree['IntranetTX']  # kbits
        self.IntranetBandwidth = tree['IntranetBandwidth']  # kbits/s
        self.InternetRX = tree['InternetRX']  # kbits
        self.InternetTX = tree['InternetTX']  # kbits
        self.InternetBandwidth = tree['InternetBandwidth']  # kbits/s
        self.IOPSRead = tree['IOPSRead']  # count/s
        self.IOPSWrite = tree['IOPSWrite']  # count/s
        self.BPSRead = tree['BPSRead']  # Byte/s
        self.BPSWrite = tree['BPSWrite']  # Byte/s
        self.TimeStamp = tree['TimeStamp']

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : InstanceStatusItemType
class InstanceStatusItemType(object):
    InstanceId = None
    Status = None

    def __deserialize__(self, tree):
        self.InstanceId = tree['InstanceId']
        self.Status = tree['Status']

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : InstanceStatusSetType
class InstanceStatusSetType(object):
    InstanceStatus = []  # InstanceStatusItemType

    def __deserialize__(self, tree):
        self.InstanceStatus = []
        instancestatus = tree['InstanceStatus']  # InstanceStatusItemType
        for instancestatusitemtype in instancestatus['InstanceStatusItemType']:
            self.InstanceStatus.append(InstanceStatusItemType(instancestatusitemtype))


    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : OperationLocksType
class OperationLocksType(object):
    LockReason = None  # financial&security

    def __deserialize__(self, tree):
        self.LockReason = tree['LockReason']  # financial&security

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : InstanceTypeItemType
class InstanceTypeItemType(object):
    InstanceTypeId = None
    CpuCoreCount = -1  #
    MemorySize = -1  # GB
    InstanceTypeFamily = None

    def __deserialize__(self, tree):
        self.InstanceTypeId = tree['InstanceTypeId']
        self.CpuCoreCount = tree['CpuCoreCount']  #
        self.MemorySize = tree['MemorySize']  # GB
        self.InstanceTypeFamily = tree['InstanceTypeFamily']

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : IpAddressSetType
class IpAddressSetType(object):
    IpAddress = None

    def __deserialize__(self, tree):
        self.IpAddress = tree

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : PermissionSetType
class PermissionSetType(object):
    Permision = None  # PermissionType

    def __deserialize__(self, tree):
        self.Permision = tree['Permision']  # PermissionType

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : PermissionType
class PermissionType(object):
    IpProtocol = None
    PortRange = None
    SourceCidrIp = None
    SourceGroupId = None
    SourceGroupOwnerAccount = None
    DestCidrIp = None
    DestGroupId = None
    DestGroupOwnerAccount = None
    Policy = None
    NicType = None
    Priority = None
    Direction = None
    Description = None

    def __deserialize__(self, tree):
        self.IpProtocol = tree['IpProtocol']
        self.PortRange = tree['PortRange']
        self.SourceCidrIp = tree['SourceCidrIp']
        self.SourceGroupId = tree['SourceGroupId']
        self.SourceGroupOwnerAccount = tree['SourceGroupOwnerAccount']
        self.DestCidrIp = tree['DestCidrIp']
        self.DestGroupId = tree['DestGroupId']
        self.DestGroupOwnerAccount = tree['DestGroupOwnerAccount']
        self.Policy = tree['Policy']
        self.NicType = tree['NicType']
        self.Priority = tree['Priority']
        self.Direction = tree['Direction']
        self.Description = tree['Description']

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : RegionType
class RegionType(object):
    RegionId = None
    LocalName = None

    def __deserialize__(self, tree):
        self.RegionId = tree['RegionId']
        self.LocalName = tree['LocalName']

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : AvailableResourceCreationType
class AvailableResourceCreationType(object):
    ResourceTypes = None  # Instance&IoOptimized&Disk&VSwitch

    def __deserialize__(self, tree):
        self.ResourceTypes = tree['ResourceTypes']  # Instance&IoOptimized&Disk&VSwitch

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : AvailableDiskCategoriesType
class AvailableDiskCategoriesType(object):
    DiskCategories = None

    def __deserialize__(self, tree):
        self.DiskCategories = tree['DiskCategories']

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : ZoneType
class ZoneType(object):
    ZoneId = None
    LocalName = None
    AvailableInstanceTypes = None  # AvailableInstanceTypesType
    AvailableResourceCreation = None  # AvailableResourceCreationType
    AvailableDiskCategories = None  # AvailableDiskCategoriesType

    def __deserialize__(self, tree):
        self.ZoneId = tree['ZoneId']
        self.LocalName = tree['LocalName']
        self.AvailableInstanceTypes = tree['AvailableInstanceTypes']  # AvailableInstanceTypesType
        self.AvailableResourceCreation = tree['AvailableResourceCreation']  # AvailableResourceCreationType
        self.AvailableDiskCategories = tree['AvailableDiskCategories']  # AvailableDiskCategoriesType

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : SnapshotType
class SnapshotType(object):
    SnapshotId = None
    SnapshotName = None
    Description = None
    Progress = None
    SourceDiskId = None
    SourceDiskSize = -1  # GB
    SourceDiskType = None
    ProductCode = None
    CreationTime = None
    Status = None
    Usage = None

    def __deserialize__(self, tree):
        self.SnapshotId = tree['SnapshotId']
        self.SnapshotName = tree['SnapshotName']
        self.Description = tree['Description']
        self.Progress = tree['Progress']
        self.SourceDiskId = tree['SourceDiskId']
        self.SourceDiskSize = tree['SourceDiskSize']  # GB
        self.SourceDiskType = tree['SourceDiskType']
        self.ProductCode = tree['ProductCode']
        self.CreationTime = tree['CreationTime']
        self.Status = tree['Status']
        self.Usage = tree['Usage']

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : SecurityGroupIdSetType
class SecurityGroupIdSetType(object):
    SecurityGroupId = None

    def __deserialize__(self, tree):
        self.SecurityGroupId = tree['SecurityGroupId']

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : SecurityGroupSetType
class SecurityGroupSetType(object):
    SecurityGroup = None  # SecurityGroupItemType

    def __deserialize__(self, tree):
        self.SecurityGroup = tree['SecurityGroup']  # SecurityGroupItemType

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : SecurityGroupItemType
class SecurityGroupItemType(object):
    SecurityGroupId = None
    SecurityGroupName = None
    Description = None
    VpcId = None
    CreationTime = None

    def __deserialize__(self, tree):
        self.SecurityGroupId = tree['SecurityGroupId']
        self.SecurityGroupName = tree['SecurityGroupName']
        self.Description = tree['Description']
        self.VpcId = tree['VpcId']
        self.CreationTime = tree['CreationTime']

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : IpRangeSetType
class IpRangeSetType(object):
    IpAddress = None
    NicType = None

    def __deserialize__(self, tree):
        self.IpAddress = tree['IpAddress']
        self.NicType = tree['NicType']

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : AutoSnapshotPolicyType
class AutoSnapshotPolicyType(object):
    SystemDiskPolicyEnabled = None
    SystemDiskPolicyTimePeriod = -1  # 1:1:00-7:00 2:7:00-13:00 3:13:00-19:00 4:19:00-1:00
    SystemDiskPolicyRetentionDays = -1  # 1,2,3day
    SystemDiskPolicyRetentionLastWeek = None
    DataDiskPolicyEnabled = None
    DataDiskPolicyTimePeriodInteger = None
    DataDiskPolicyRetentionDays = -1  # 1,2,3day
    DataDiskPolicyRetentionLastWeek = None

    def __deserialize__(self, tree):
        self.SystemDiskPolicyEnabled = tree['SystemDiskPolicyEnabled']
        self.SystemDiskPolicyTimePeriod = tree['SystemDiskPolicyTimePeriod']  # 1:1:00-7:00 2:7:00-13:00 3:13:00-19:00 4:19:00-1:00
        self.SystemDiskPolicyRetentionDays = tree['SystemDiskPolicyRetentionDays']  # 1,2,3day
        self.SystemDiskPolicyRetentionLastWeek = tree['SystemDiskPolicyRetentionLastWeek']
        self.DataDiskPolicyEnabled = tree['DataDiskPolicyEnabled']
        self.DataDiskPolicyTimePeriodInteger = tree['DataDiskPolicyTimePeriodInteger']
        self.DataDiskPolicyRetentionDays = tree['DataDiskPolicyRetentionDays']  # 1,2,3day
        self.DataDiskPolicyRetentionLastWeek = tree['DataDiskPolicyRetentionLastWeek']

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : AutoSnapshotExecutionStatusType
class AutoSnapshotExecutionStatusType(object):
    SystemDiskExecutionStatus = None
    DataDiskExecutionStatus = None

    def __deserialize__(self, tree):
        self.SystemDiskExecutionStatus = tree['SystemDiskExecutionStatus']
        self.DataDiskExecutionStatus = tree['DataDiskExecutionStatus']

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : DiskDeviceMapping
class DiskDeviceMapping(object):
    SnapshotId = None
    Size = None
    Device = None
    Format = None
    ImportOSSBucket = None
    ImportOSSObject = None

    def __deserialize__(self, tree):
        self.SnapshotId = tree['SnapshotId']
        self.Size = tree['Size']
        self.Device = tree['Device']
        self.Format = tree['Format']
        self.ImportOSSBucket = tree['ImportOSSBucket']
        self.ImportOSSObject = tree['ImportOSSObject']

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : VpcSetType
class VpcSetType(object):
    VpcId = None
    RegionId = None
    Status = None
    VpcName = None
    VSwitchIds = None
    CidrBlock = None
    VRouterId = None
    Description = None
    CreationTime = None

    def __deserialize__(self, tree):
        self.VpcId = tree['VpcId']
        self.RegionId = tree['RegionId']
        self.Status = tree['Status']
        self.VpcName = tree['VpcName']
        self.VSwitchIds = tree['VSwitchIds']
        self.CidrBlock = tree['CidrBlock']
        self.VRouterId = tree['VRouterId']
        self.Description = tree['Description']
        self.CreationTime = tree['CreationTime']

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : VRouterSetType
class VRouterSetType(object):
    VRouterId = None
    RegionId = None
    VpcId = None
    RouteTableIds = None
    VRouterName = None
    Description = None
    CreationTime = None

    def __deserialize__(self, tree):
        self.VRouterId = tree['VRouterId']
        self.RegionId = tree['RegionId']
        self.VpcId = tree['VpcId']
        self.RouteTableIds = tree['RouteTableIds']
        self.VRouterName = tree['VRouterName']
        self.Description = tree['Description']
        self.CreationTime = tree['CreationTime']

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : RouteTableSetType
class RouteTableSetType(object):
    VRouterId = None
    RouteTableId = None
    RouteEntrys = []  # RouteEntrySetType
    RouteTableType = None
    CreationTime = None

    def __deserialize__(self, tree):
        self.VRouterId = tree['VRouterId']
        self.RouteTableId = tree['RouteTableId']
        self.RouteEntrys = []
        routeentrys = tree['RouteEntrys']  # RouteEntrySetType
        for routeentrysettype in routeentrys['RouteEntrySetType']:
            self.RouteEntrys.append(RouteEntrySetType(routeentrysettype))

        self.RouteTableType = tree['RouteTableType']
        self.CreationTime = tree['CreationTime']

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : RouteEntrySetType
class RouteEntrySetType(object):
    RouteTableId = None
    DestinationCidrBlock = None
    Type = None
    NextHopType = None
    NextHopId = None
    Status = None

    def __deserialize__(self, tree):
        self.RouteTableId = tree['RouteTableId']
        self.DestinationCidrBlock = tree['DestinationCidrBlock']
        self.Type = tree['Type']
        self.NextHopType = tree['NextHopType']
        self.NextHopId = tree['NextHopId']
        self.Status = tree['Status']

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : VSwitchSetType
class VSwitchSetType(object):
    VSwitchId = None
    VpcId = None
    Status = None
    CidrBlock = None
    ZoneId = None
    AvailableIpAddressCount = -1
    Description = None
    VSwitchName = None
    CreationTime = None

    def __deserialize__(self, tree):
        self.VSwitchId = tree['VSwitchId']
        self.VpcId = tree['VpcId']
        self.Status = tree['Status']
        self.CidrBlock = tree['CidrBlock']
        self.ZoneId = tree['ZoneId']
        self.AvailableIpAddressCount = tree['AvailableIpAddressCount']
        self.Description = tree['Description']
        self.VSwitchName = tree['VSwitchName']
        self.CreationTime = tree['CreationTime']

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : EipAddressAssociateType
class EipAddressAssociateType(object):
    AllocationId = None
    IpAddress = None
    BandwidthInteger = None
    InternetChargeType = None

    def __deserialize__(self, tree):
        self.AllocationId = tree['AllocationId']
        self.IpAddress = tree['IpAddress']
        self.BandwidthInteger = tree['BandwidthInteger']
        self.InternetChargeType = tree['InternetChargeType']

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : EipAddressSetType
class EipAddressSetType(object):
    RegionId = None
    IpAddress = None
    AllocationId = None
    Status = None
    InstanceType = None
    InstanceId = None
    Bandwidth = -1  # 5Mbps
    InternetChargeType = None
    OperationLocks = None  # OperationLocksType
    AllocationTime = None

    def __deserialize__(self, tree):
        self.RegionId = tree['RegionId']
        self.IpAddress = tree['IpAddress']
        self.AllocationId = tree['AllocationId']
        self.Status = tree['Status']
        self.InstanceType = tree['InstanceType']
        self.InstanceId = tree['InstanceId']
        self.Bandwidth = tree['Bandwidth']  # 5Mbps
        self.InternetChargeType = tree['InternetChargeType']
        self.OperationLocks = tree['OperationLocks']  # OperationLocksType
        self.AllocationTime = tree['AllocationTime']

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : InstanceAttributesType
class InstanceAttributesType(object):
    InstanceId = None
    InstanceName = None
    Description = None
    ImageId = None
    RegionId = None
    ZoneId = None
    CPU = -1
    Memory = -1  # MB
    InstanceType = None
    InstanceTypeFamily = None
    HostName = None
    SerialNumber = None
    Status = None
    SecurityGroupIds = None  # SecurityGroupIdSetType
    PublicIpAddress = []  # IpAddressSetType
    InternetMaxBandwidthIn = -1
    InternetMaxBandwidthOut = -1
    InternetChargeType = None
    CreationTime = None
    VpcAttributes = None  # VpcAttributesType
    EipAddress = None  # EipAddressAssociateType
    InnerIpAddress = []  # IpAddressSetType
    InstanceNetworkType = None
    OperationLocks = None
    InstanceChargeType = None
    DeviceAvailable = None
    IoOptimized = None
    ExpiredTime = None

    def __deserialize__(self, tree):
        self.InstanceId = tree['InstanceId']
        self.InstanceName = tree['InstanceName']
        self.Description = tree['Description']
        self.ImageId = tree['ImageId']
        self.RegionId = tree['RegionId']
        self.ZoneId = tree['ZoneId']
        self.CPU = tree['Cpu']
        self.Memory = tree['Memory']  # MB
        self.InstanceType = tree['InstanceType']
        self.InstanceTypeFamily = tree['InstanceTypeFamily']
        self.HostName = tree['HostName']
        self.SerialNumber = tree['SerialNumber']
        self.Status = tree['Status']
        self.SecurityGroupIds = tree['SecurityGroupIds']  # SecurityGroupIdSetType
        self.PublicIpAddress = []
        publicipaddress = tree['PublicIpAddress']  # IpAddressSetType
        for ipaddresssettype in publicipaddress['IpAddress']:
            self.PublicIpAddress.append(IpAddressSetType(ipaddresssettype))

        self.InternetMaxBandwidthIn = tree['InternetMaxBandwidthIn']
        self.InternetMaxBandwidthOut = tree['InternetMaxBandwidthOut']
        self.InternetChargeType = tree['InternetChargeType']
        self.CreationTime = tree['CreationTime']
        self.VpcAttributes = tree['VpcAttributes']  # VpcAttributesType
        self.EipAddress = tree['EipAddress']  # EipAddressAssociateType
        self.InnerIpAddress = []
        inneripaddress = tree['InnerIpAddress']  # IpAddressSetType
        for ipaddresssettype in inneripaddress['IpAddress']:
            self.InnerIpAddress.append(IpAddressSetType(ipaddresssettype))

        self.InstanceNetworkType = tree['InstanceNetworkType']
        self.OperationLocks = tree['OperationLocks']
        self.InstanceChargeType = tree['InstanceChargeType']
        self.DeviceAvailable = tree['DeviceAvailable']
        self.IoOptimized = tree['IoOptimized']
        self.ExpiredTime = tree['ExpiredTime']

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : VpcAttributesType
class VpcAttributesType(object):
    VpcId = None
    VSwitchId = None
    PrivateIpAddress = None  # IpAddressSetType
    NatIpAddress = None

    def __deserialize__(self, tree):
        self.VpcId = tree['VpcId']
        self.VSwitchId = tree['VSwitchId']
        self.PrivateIpAddress = tree['PrivateIpAddress']  # IpAddressSetType
        self.NatIpAddress = tree['NatIpAddress']

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : EipMonitorDataType
class EipMonitorDataType(object):
    EipRX = -1  # bytes
    EipTX = -1  # bytes
    EipFlow = -1  # bytes
    EipBandwidth = -1  # bytes/s
    EipPackets = -1
    TimeStamp = None

    def __deserialize__(self, tree):
        self.EipRX = tree['EipRX']  # bytes
        self.EipTX = tree['EipTX']  # bytes
        self.EipFlow = tree['EipFlow']  # bytes
        self.EipBandwidth = tree['EipBandwidth']  # bytes/s
        self.EipPackets = tree['EipPackets']
        self.TimeStamp = tree['TimeStamp']

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : DiskMonitorDataType
class DiskMonitorDataType(object):
    DiskId = None
    IOPSRead = -1  # /s
    IOPSWrite = -1  # /s
    IOPSTotal = -1  # /s
    BPSRead = -1  # byte/s
    BPSWrite = -1  # byte/s
    BPSTotal = -1  # byte/s
    TimeStamp = None

    def __deserialize__(self, tree):
        self.DiskId = tree['DiskId']
        self.IOPSRead = tree['IOPSRead']  # /s
        self.IOPSWrite = tree['IOPSWrite']  # /s
        self.IOPSTotal = tree['IOPSTotal']  # /s
        self.BPSRead = tree['BPSRead']  # byte/s
        self.BPSWrite = tree['BPSWrite']  # byte/s
        self.BPSTotal = tree['BPSTotal']  # byte/s
        self.TimeStamp = tree['TimeStamp']

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : AccountType
class AccountType(object):
    AliyunId = None

    def __deserialize__(self, tree):
        self.AliyunId = tree['AliyunId']

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : ShareGroupType
class ShareGroupType(object):
    Group = None

    def __deserialize__(self, tree):
        self.Group = tree['Group']

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : TagSetItem
class TagSetItem(object):
    TagKey = None
    TagValue = None

    def __deserialize__(self, tree):
        self.TagKey = tree['TagKey']
        self.TagValue = tree['TagValue']

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : ResSetItem
class ResSetItem(object):
    ResourceId = None
    ResourceType = None
    RegionId = None

    def __deserialize__(self, tree):
        self.ResourceId = tree['ResourceId']
        self.ResourceType = tree['ResourceType']
        self.RegionId = tree['RegionId']

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : HaVipSetType
class HaVipSetType(object):
    HaVipSetTypes = []  # HaVipSetType

    def __deserialize__(self, tree):
        self.HaVipSetTypes = []
        havipsettypes = tree['HaVipSetTypes']  # HaVipSetType
        for havipsettype in havipsettypes['HaVipSetType']:
            self.HaVipSetTypes.append(HaVipSetType(havipsettype))


    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : HaVipItemType
class HaVipItemType(object):
    HaVipId = None
    RegionId = None
    VpcId = None
    VSwitchId = None
    IpAddress = None
    Status = None
    AssociatedInstances = None
    MasterInstanceId = None
    AssociatedEipAddresses = None
    Description = None
    CreationTime = None

    def __deserialize__(self, tree):
        self.HaVipId = tree['HaVipId']
        self.RegionId = tree['RegionId']
        self.VpcId = tree['VpcId']
        self.VSwitchId = tree['VSwitchId']
        self.IpAddress = tree['IpAddress']
        self.Status = tree['Status']
        self.AssociatedInstances = tree['AssociatedInstances']
        self.MasterInstanceId = tree['MasterInstanceId']
        self.AssociatedEipAddresses = tree['AssociatedEipAddresses']
        self.Description = tree['Description']
        self.CreationTime = tree['CreationTime']

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : AvailableInstanceTypesType
class AvailableInstanceTypesType(object):
    InstanceTypes = None

    def __deserialize__(self, tree):
        self.InstanceTypes = tree['InstanceTypes']

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : InstanceTypeFamilyItemType
class InstanceTypeFamilyItemType(object):
    InstanceTypeFamilyId = None
    Generation = None

    def __deserialize__(self, tree):
        self.InstanceTypeFamilyId = tree['InstanceTypeFamilyId']
        self.Generation = tree['Generation']

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : RouterInterfaceSetType
class RouterInterfaceSetType(object):
    RouterInterfaceSetTypes = []  # RouterInterfaceSetType

    def __deserialize__(self, tree):
        self.RouterInterfaceSetTypes = []
        routerinterfacesettypes = tree['RouterInterfaceSetTypes']  # RouterInterfaceSetType
        for routerinterfacesettype in routerinterfacesettypes['RouterInterfaceSetType']:
            self.RouterInterfaceSetTypes.append(RouterInterfaceSetType(routerinterfacesettype))


    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : RouterInterfaceItemType
class RouterInterfaceItemType(object):
    RouterInterfaceId = None
    OppositeRegionId = None
    Role = None
    Spec = None
    Name = None
    Description = None
    RouterId = None
    RouterType = None
    CreationTime = None
    Status = None
    BusinessStatus = None
    ConnectedTime = None
    OppositeInterfaceId = None
    OppositeInterfaceSpec = None
    OppositeInterfaceStatus = None
    OppositeInterfaceBusinessStatus = None
    OppositeRouterId = None
    OppositeRouterType = None
    OppositeInterfaceOwnerId = None

    def __deserialize__(self, tree):
        self.RouterInterfaceId = tree['RouterInterfaceId']
        self.OppositeRegionId = tree['OppositeRegionId']
        self.Role = tree['Role']
        self.Spec = tree['Spec']
        self.Name = tree['Name']
        self.Description = tree['Description']
        self.RouterId = tree['RouterId']
        self.RouterType = tree['RouterType']
        self.CreationTime = tree['CreationTime']
        self.Status = tree['Status']
        self.BusinessStatus = tree['BusinessStatus']
        self.ConnectedTime = tree['ConnectedTime']
        self.OppositeInterfaceId = tree['OppositeInterfaceId']
        self.OppositeInterfaceSpec = tree['OppositeInterfaceSpec']
        self.OppositeInterfaceStatus = tree['OppositeInterfaceStatus']
        self.OppositeInterfaceBusinessStatus = tree['OppositeInterfaceBusinessStatus']
        self.OppositeRouterId = tree['OppositeRouterId']
        self.OppositeRouterType = tree['OppositeRouterType']
        self.OppositeInterfaceOwnerId = tree['OppositeInterfaceOwnerId']

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : AvailableResourceType
class AvailableResourceType(object):
    IoOptimized = None
    Network = None
    DiskCategory = None
    InstanceType = None

    def __deserialize__(self, tree):
        self.IoOptimized = tree['IoOptimized']
        self.Network = tree['Network']
        self.DiskCategory = tree['DiskCategory']
        self.InstanceType = tree['InstanceType']

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : TaskType
class TaskType(object):
    TaskId = None
    Action = None
    TaskStatus = None
    SupportCancel = None
    CreationTime = None
    FinishedTime = None

    def __deserialize__(self, tree):
        self.TaskId = tree['TaskId']
        self.Action = tree['Action']
        self.TaskStatus = tree['TaskStatus']
        self.SupportCancel = tree['SupportCancel']
        self.CreationTime = tree['CreationTime']
        self.FinishedTime = tree['FinishedTime']

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : OperationProgress
class OperationProgress(object):
    RelatedItemSet = None  # RelatedItemSetType
    OperationStatus = None
    ErrorCode = None
    ErrorMsg = None

    def __deserialize__(self, tree):
        self.RelatedItemSet = tree['RelatedItemSet']  # RelatedItemSetType
        self.OperationStatus = tree['OperationStatus']
        self.ErrorCode = tree['ErrorCode']
        self.ErrorMsg = tree['ErrorMsg']

    def __init__(self, tree):
        self.__deserialize__(tree)


#Aliyun Data Type : RelatedItemType
class RelatedItemType(object):
    Name = None
    Value = None

    def __deserialize__(self, tree):
        self.Name = tree['Name']
        self.Value = tree['Value']

    def __init__(self, tree):
        self.__deserialize__(tree)



# Process finished with exit code 0



# -----------------------------------------------------------------------------------
class AliyunDescribeInstances(AliyunRequestId):
    Instances = []

    def __init__(self, tree):
        self.__deserialize__(tree)

    def __deserialize__(self, tree):
        print "Class AliyunDescribeInstances Method __deserialize__ Debug:run"
        # init super class
        super(AliyunDescribeInstances, self).__init__(tree)

        instances = tree['Instances']
        self.Instances = []
        for instance in instances['Instance']:
            self.Instances.append(InstanceAttributesType(instance))

        print "Class AliyunDescribeInstances Method __deserialize__ Debug:run"


class AliyunDescribeInstanceTypes(AliyunRequestId):
    InstanceTypes = []

    def __init__(self, tree):
        self.__deserialize__(tree)

    def __deserialize__(self, tree):
        print "Class AliyunDescribeInstanceTypes Method __deserialize__ Debug:run"
        # init super class
        super(AliyunDescribeInstanceTypes, self).__init__(tree)

        InstanceTypes = tree['InstanceTypes']
        self.InstanceTypes = []
        for instanceType in InstanceTypes['InstanceType']:
            self.InstanceTypes.append(InstanceTypeItemType(instanceType))

        print "Class AliyunDescribeInstanceTypes Method __deserialize__ Debug:run"

class AliyunDescribeDisks(AliyunPage,AliyunRequestId):
    Disks = []

    def __init__(self, tree):
        self.__deserialize__(tree)

    def __deserialize__(self, tree):
        print "Class AliyunDescribeDisks Method __deserialize__ Debug:run"
        # init super class
        super(AliyunDescribeDisks, self).__init__(tree)

        disks = tree['Disks']
        self.Disks = []
        for disk in disks['Disk']:
            self.Disks.append(DiskItemType(disk))

        print "Class AliyunDescribeDisks Method __deserialize__ Debug:run"

class AliyunDescribeSnapshots(AliyunPage, AliyunRequestId):
    Snapshots = []

    def __init__(self, tree):
        self.__deserialize__(tree)

    def __deserialize__(self, tree):
        print "Class AliyunDescribeImages Method __deserialize__ Debug:run"
        # init super class
        super(AliyunDescribeSnapshots, self).__init__(tree)

        snapshots = tree['Snapshots']
        self.Snapshots = []
        for snapshot in snapshots['Snapshot']:
            self.Snapshots.append(SnapshotType(snapshot))

        print "Class AliyunDescribeImages Method __deserialize__ Debug:run"

class AliyunDescribeRegions(AliyunRequestId):
    Regions = []

    def __init__(self, tree):
        self.__deserialize__(tree)

    def __deserialize__(self, tree):
        print "Class AliyunDescribeRegionsResponse Method __deserialize__ Debug:run"
        # init super class
        super(AliyunDescribeRegions, self).__init__(tree)

        regions = tree['Regions']
        self.Regions = []
        for region in regions['Region']:
            self.Regions.append(RegionType(region))

        print "Class AliyunDescribeRegionsResponse Method __deserialize__ Debug:run"

class AliyunDescribeZones(AliyunRequestId):
    Zones = []

    def __init__(self, tree):
        self.__deserialize__(tree)

    def __deserialize__(self, tree):
        print "Class AliyunDescribeRegionsResponse Method __deserialize__ Debug:run"
        # init super class
        super(AliyunDescribeZones, self).__init__(tree)

        zones = tree['Zones']
        self.Zones = []
        for zone in zones['Zone']:
            self.Zones.append(ZoneType(zone))

        print "Class AliyunDescribeRegionsResponse Method __deserialize__ Debug:run"

class AliyunDescribeImages(AliyunPage, AliyunRequestId):
    Images = []

    def __init__(self, tree):
        self.__deserialize__(tree)

    def __deserialize__(self, tree):
        print "Class AliyunDescribeImages Method __deserialize__ Debug:run"
        # init super class
        super(AliyunDescribeImages, self).__init__(tree)

        images = tree['Images']
        self.Images = []
        for image in images['Image']:
            self.Images.append(ImageType(image))

        print "Class AliyunDescribeImages Method __deserialize__ Debug:run"

class AliyunDescribeSecurityGroups(AliyunPage,AliyunRequestId):
    SecurityGroups = []

    def __init__(self, tree):
        self.__deserialize__(tree)

    def __deserialize__(self, tree):
        print "Class AliyunDescribeImages Method __deserialize__ Debug:run"
        # init super class
        super(AliyunDescribeSecurityGroups, self).__init__(tree)

        securityGroups = tree['SecurityGroups']
        self.SecurityGroups = []
        for securityGroup in securityGroups['SecurityGroups']:
            self.SecurityGroups.append(SecurityGroupItemType(securityGroup))

        print "Class AliyunDescribeImages Method __deserialize__ Debug:run"